package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.IHotArticleService;
import com.heima.behavior.dto.ArticleAggregatorResult;
import com.heima.behavior.dto.ArticleOperationMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author: itheima
 * @create: 2022-08-10 16:10
 */
@Slf4j
@Component
public class HotArticleResultListener {

    @Autowired
    private IHotArticleService hotArticleService;

    /**
     * 实时监听实时流式计算热点文章增量值
     *
     * @param record {"articleId":1553932231364395009,"collect":1,"comment":1,"like":2,"view":0}
     */
    @KafkaListener(topics = "${topic.hotArticleResultTopic}")
    public void handleMessage(ConsumerRecord<String, String> record) {
        if (StringUtils.isNotBlank(record.value())) {
            log.info("【文章微服务】监听实时计算结果：{}", record.value());
            //获取消息，将消息JSON字符串反序列化为 ArticleStreamMessage
            ArticleAggregatorResult aggregatorResult = JSON.parseObject(record.value(), ArticleAggregatorResult.class);
            //更新Redis缓存 数据库文章操作行为值
            hotArticleService.updateCacheAndDB(aggregatorResult);
        }
    }
}
